from api import ApiServer
from db_model import Poll
import json
import opensocial

from contactserver import ContactServer
from pollserver import PollServer
from recordserver import RecordServer
from commentserver import CommentServer

class DisplayServer(ApiServer):
  def get(self):
    list_type = self.request.get('list_type')
    output = []
    if list_type == 'pollsoffriend':
      # Example Query:
      # /display?list_type=pollsoffriend&
      #                   [opensocial_viewer_id=[ID]]
      self._PollsOfFriends(output)
    elif list_type == 'optionsofpoll':
      # Example Query:
      # /display?list_type=optionsofpoll&
      #          poll_id=[KEY]&
      #         [opensocial_viewer_id=[ID]]
      self._OptionsOfPoll(output)
    elif list_type == 'pollsofuser':
      # Example Query:
      # /display?list_type=pollsofuser&
      #          creator_id=[ID]&
      #         [opensocial_viewer_id=[ID]]
      self._PollsOfUser(self.request.get("creator_id"), None, output)
    elif list_type == 'testsocial':
      self._handlesocial(output)
    self.response.out.write(json.write(output))

  def _handlesocial(self, output):
    # TODO(microat): remove it
    viewer_id = self.request.get('opensocial_viewer_id')
    friend_names = []
    try:
      friends = self._get_friends_data(viewer_id)
      if friends:
        for person in friends:
          friend_names.append([person.get_id(), person.get_display_name()])
    except:
      pass

    output.append({
      'opensocial_viewer_id':viewer_id,
      'opensocial_owner_id':self.request.get('opensocial_owner_id'),
      'opensocial_app_url':self.request.get('opensocial_app_url'),
      'opensocial_app_url':self.request.get('opensocial_app_url'),
      'opensocial_instance_id':self.request.get('opensocial_instance_id'),
      'opensocial_app_id':self.request.get('opensocial_app_id'),
      'xoauth_public_key':self.request.get('xoauth_public_key'),
      #'api_id':me.get_id(),
      #'display_name':me.get_display_name(),
      'friend_list':friend_names
    })

  # Returns output.append({creator_id:[id],
  #                       description:[text],
  #                       poll_id:[id]})
  def _PollsOfUser(self, user_id, user_name, output):
    viewer_id = self.request.get('opensocial_viewer_id')
    results = Poll.gql('WHERE creator_id=:user_id', user_id=user_id)
    for poll in results:
      if self._checkPollAccess(poll, viewer_id):
        out = {'creator_id': user_id,
               'creator_name': user_name,
               'description': poll.description,
               'poll_id': str(poll.key())}
        output.append(out)

  # Returns output += [{creator_id:[id],
  #                     description:[text],
  #                     poll_id:[id]}]
  def _PollsOfFriends(self, output):
    viewer_id = self.request.get('opensocial_viewer_id')
    try:
      friends = self._get_friends_data(viewer_id)
      me = self._get_user_data(self.request.get('opensocial_viewer_id'))
      ifiammyfriend = False
      for friend in friends:
        if me.get_id() == friend.get_id():
          ifiammyfriend = True
          break
      if not ifiammyfriend:
        self._PollsOfUser(me.get_id(), me.get_display_name(), output)
      for friend in friends:
        self._PollsOfUser(friend.get_id(), friend.get_display_name(), output)
    except:
        self._PollsOfUser(viewer_id, 'me', output)

  # Returns output.append([options[text]])
  def _OptionsOfPoll(self, output):
    viewer_id = self.request.get('opensocial_viewer_id')
    poll_id = self.request.get("poll_id")
    if poll_id:
      poll = Poll.get(poll_id)
      if poll and self._checkPollAccess(poll, viewer_id):
        output+=poll.options
